package com.subumbo.audio.loader
{
	import __AS3__.vec.Vector;
	
	import com.subumbo.audio.vo.SoundsVO;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.media.Sound;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;

	public class AudioLoader extends EventDispatcher
	{
		private var _basePath:String = "";
		private var _urls:Vector.<String>;
		private var _sounds:Vector.<Sound> = new Vector.<Sound>();
		private var _soundData:Vector.<ByteArray>;
		private var _ldr:Sound;
		private var count:uint = 0;
		
		public var loaded:Boolean;
		
		public function AudioLoader(model:SoundsVO)
		{
			_basePath = model.basePath;
			_urls = model.urls;
		}

		private function loadSounds():void
		{
			_ldr = new Sound();
			_ldr.addEventListener(Event.COMPLETE, onLoadComplete);
			_ldr.addEventListener(ProgressEvent.PROGRESS, onProgress, false, 0, true);
			//_ldr.addEventListener(IOErrorEvent.IO_ERROR, IOError, false, 0, true);
			_ldr.load(new URLRequest(_basePath + "/" + _urls[count] + ".mp3"));
			trace(_basePath + "/" + _urls[count] + ".mp3");
		}
		
		protected function onLoadComplete(e:Event):void
		{
			_sounds.push(_ldr);
			_ldr.removeEventListener(Event.COMPLETE, onLoadComplete);
			_ldr.removeEventListener(IOErrorEvent.IO_ERROR, IOError);
			_ldr = null
			
			if(count == _urls.length -1)
			{	
				trace("LOADED");
				loaded = true;			
				dispatchEvent(new Event(Event.COMPLETE));
			}
			if(count < _urls.length - 1)
			{
				count++
				loadSounds();				
			}	
		}
		
		public function getBytes():Vector.<ByteArray>
		{	
			_soundData = new Vector.<ByteArray>();
			for(var j:uint = 0; j < _sounds.length; j++)
				_soundData.push(new ByteArray());
			
			for(var i:uint = 0; i < _sounds.length; i++)
			{
				var sound:Sound = _sounds[i];
				var l:Number = Math.floor(sound.length * 44.1 *8)
				sound.extract(_soundData[i], l);
			}
			
			for(var n:uint = 0; n < _soundData.length; n++)
				_soundData[n].position = 0;
			return _soundData;
		}
		
		protected function onProgress(e:ProgressEvent):void
		{
			trace(e.bytesLoaded + " / " + e.bytesTotal);
		}
		
		protected function IOError(e:IOErrorEvent):void
		{
			throw new Error("Audioloader: IOError");
		}
		
		public function load():void
		{
			loadSounds();
			/* if(!loaded) loadSounds();
			else dispatchEvent(new Event(Event.COMPLETE)); */
		}
		
		public function getSounds():Vector.<Sound> { return _sounds; }
		
	}
}